package com.itheima.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.itheima.constant.MessageConstant;
import com.itheima.entity.Result;
import com.itheima.pojo.OrderSetting;
import com.itheima.service.OrderSettingService;
import com.itheima.utils.POIUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 预约设置控制层
 */
@RestController
@RequestMapping("/ordersetting")
public class OrderSettingController {

    @Reference
    private OrderSettingService orderSettingService;


    /**
     * 批量导入预约设置
     *
     * @param excelFile
     * @return
     */
    @PostMapping("/upload")
    public Result upload(@RequestParam("excelFile") MultipartFile excelFile) {
        //POI工具类读取上传文件
        try {
            List<String[]> excel = POIUtils.readExcel(excelFile);
            //获取的字符串集合转成pojo集合
            List<OrderSetting> list = new ArrayList<>();
            if (excel != null && excel.size() > 0) {
                for (String[] row : excel) {
                    OrderSetting orderSetting = new OrderSetting();
                    Date date = new Date(row[0]);
                    orderSetting.setOrderDate(date);
                    int number = Integer.parseInt(row[1]);
                    orderSetting.setNumber(number);
                    list.add(orderSetting);
                }
            }
            //调用service处理设置请求
            orderSettingService.add(list);
            return new Result(true, MessageConstant.IMPORT_ORDERSETTING_SUCCESS);
        } catch (IOException e) {
            e.printStackTrace();
            return new Result(false, MessageConstant.IMPORT_ORDERSETTING_FAIL);
        }
    }

    /**
     * 显示预约设置
     *
     * @param date
     * @return
     */
    @PostMapping("getOrderSettingByMonth")
    public Result getOrderSettingByMonth(String date) {
        try {
            List<Map> mapList = orderSettingService.getOrderSettingByMonth(date);
            return new Result(true, MessageConstant.QUERY_ORDER_SUCCESS, mapList);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, MessageConstant.QUERY_ORDER_FAIL);
        }
    }

    /**
     * 编辑按钮修改预约信息
     * @param orderSetting
     * @return
     */
    @PostMapping("/editNumberByDate")
    public Result editNumberByDate(@RequestBody OrderSetting orderSetting) {
        try {
            orderSettingService.editNumberByDate(orderSetting);
            return new Result(true, MessageConstant.ORDERSETTING_SUCCESS);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, MessageConstant.ORDERSETTING_FAIL);
        }
    }

}

